#!/bin/bash

# AIDE OpenAI 连接问题修复脚本 (Linux/macOS)

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
GRAY='\033[0;37m'
NC='\033[0m' # No Color

echo -e "${BLUE}======================================"
echo -e "AIDE OpenAI 连接问题诊断与修复工具"
echo -e "======================================${NC}"
echo ""

# 检查 .env.prod 文件
if [ ! -f ".env.prod" ]; then
    echo -e "${RED}❌ 错误: .env.prod 文件不存在${NC}"
    echo -e "${YELLOW}正在从模板创建...${NC}"
    cp env-prod-template.txt .env.prod
    echo -e "${GREEN}✅ 已创建 .env.prod 文件，请编辑其中的配置${NC}"
    echo ""
fi

# 检查 OpenAI 配置
echo -e "${BLUE}🔍 检查 OpenAI 配置...${NC}"

OPENAI_KEY=$(grep "OPENAI_API_KEY=" .env.prod | cut -d'=' -f2 | tr -d ' ')
OPENAI_BASE_URL=$(grep "OPENAI_BASE_URL=" .env.prod | cut -d'=' -f2 | tr -d ' ')
OPENAI_MODEL=$(grep "OPENAI_MODEL=" .env.prod | cut -d'=' -f2 | tr -d ' ')

echo -e "${CYAN}📋 当前 OpenAI 配置:${NC}"
if [ -n "$OPENAI_KEY" ] && [ "$OPENAI_KEY" != "sk-your_openai_api_key_here" ]; then
    echo "   API Key: ${OPENAI_KEY:0:10}..."
else
    echo -e "   API Key: ${RED}❌ 未配置${NC}"
fi

if [ -n "$OPENAI_BASE_URL" ]; then
    echo "   Base URL: $OPENAI_BASE_URL"
else
    echo -e "   Base URL: ${RED}❌ 未配置${NC}"
fi

if [ -n "$OPENAI_MODEL" ]; then
    echo "   Model: $OPENAI_MODEL"
else
    echo -e "   Model: ${RED}❌ 未配置${NC}"
fi
echo ""

# 检查配置是否完整
NEEDS_CONFIG=false
if [ -z "$OPENAI_KEY" ] || [ "$OPENAI_KEY" = "sk-your_openai_api_key_here" ]; then
    echo -e "${YELLOW}⚠️ OPENAI_API_KEY 需要配置${NC}"
    NEEDS_CONFIG=true
fi
if [ -z "$OPENAI_BASE_URL" ]; then
    echo -e "${YELLOW}⚠️ OPENAI_BASE_URL 需要配置${NC}"
    NEEDS_CONFIG=true
fi

if [ "$NEEDS_CONFIG" = true ]; then
    echo ""
    echo -e "${YELLOW}📝 请手动编辑 .env.prod 文件，设置正确的 OpenAI 配置:${NC}"
    echo -e "${GRAY}   nano .env.prod${NC}"
    echo ""
    
    read -p "配置完成后，按 Enter 继续测试，或输入 'q' 退出: " continue
    if [ "$continue" = "q" ]; then
        exit 0
    fi
fi

echo -e "${BLUE}🔧 修复 Docker 配置...${NC}"

# 检测操作系统
if [[ "$OSTYPE" == "msys" || "$OSTYPE" == "win32" ]]; then
    COMPOSE_OVERRIDE="docker-compose.windows.yml"
else
    COMPOSE_OVERRIDE="docker-compose.linux.yml"
fi

# 重新构建并启动后端服务
echo -e "${BLUE}正在重新构建后端服务...${NC}"
if docker-compose -f docker-compose.prod.yml -f "$COMPOSE_OVERRIDE" --env-file .env.prod up -d --build backend; then
    echo -e "${GREEN}✅ 后端服务已重新构建${NC}"
else
    echo -e "${RED}❌ 重新构建失败${NC}"
    exit 1
fi

# 等待服务启动
echo -e "${BLUE}等待服务启动...${NC}"
sleep 15

# 在容器内运行 OpenAI 连接测试
echo -e "${BLUE}🧪 运行容器内 OpenAI 连接测试...${NC}"
echo ""

if docker exec aide-backend-prod node test-openai-docker.js; then
    echo ""
    echo -e "${GREEN}✅ OpenAI 连接测试完成${NC}"
else
    echo -e "${RED}❌ 容器内测试失败${NC}"
    echo ""
    echo -e "${YELLOW}🔍 查看后端服务日志:${NC}"
    docker logs --tail 50 aide-backend-prod
fi

echo ""
echo -e "${BLUE}======================================"
echo -e "修复完成"
echo -e "======================================${NC}"

echo ""
echo -e "${YELLOW}💡 如果仍有问题，可能的原因:${NC}"
echo "   1. 网络防火墙阻止了容器访问外部 API"
echo "   2. 代理设置需要配置"
echo "   3. OpenAI API 端点不可达"
echo "   4. API Key 无效或权限不足"
echo ""
echo -e "${CYAN}🔧 进一步排查:${NC}"
echo "   查看完整日志: docker logs aide-backend-prod"
echo "   进入容器调试: docker exec -it aide-backend-prod sh"
echo "   测试网络连接: docker exec aide-backend-prod ping ai-api.unidtai.com"
